<template>
  <div class="add-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>

      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        label-position="top"
        :model="addRuleForm"
        :rules="addRules"
        ref="addRuleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-tabs @tab-click="tabClick" :before-leave="beforeLeave" v-model="activeIndex" :tab-position="'left'">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addRuleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addRuleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addRuleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addRuleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader 
                @change="changeCate"
                :props="cateProps"
                v-model="addRuleForm.goods_cat"
                :options="cateList" 
                :show-all-levels="false">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in addRuleForm.manyAttr" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(checkname, i) in item.attr_vals" :key="i" :label="checkname"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in addRuleForm.onlyAttr" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :headers="uploadObj"
              :action="uploadURL"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="addRuleForm.fileList"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor 
              v-model="addRuleForm.goods_introduce"
              ref="myQuillEditor">
            </quill-editor>
            <el-button class="add-good" type="primary" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog
      title="预览图片"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img width="100%" :src="previewImg" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      previewDialogVisible: false,
      previewImg: '',
      uploadObj: {
        Authorization: sessionStorage.getItem('token') || ''
      },
      uploadURL: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      activeIndex: '0',
      addRuleForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        manyAttr: [],
        onlyAttr: [],
        fileList: [],
        pics: [],
        goods_introduce: ''
      },
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      }
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get(`categories`)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.cateList = res.data
    },
    changeCate () {
      if(this.addRuleForm.goods_cat.length !== 3) {
        this.addRuleForm.goods_cat = []
      }
    },
    beforeLeave (nowName, oldName) {
      if(oldName === '0' && this.addRuleForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    async tabClick () {
      if(this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })

        this.addRuleForm.manyAttr = res.data

      } else if(this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.addRuleForm.onlyAttr = res.data
      }
    },
    handleRemove (file, fileList) {
      let i = this.addRuleForm.pics.findIndex(function(item){
        return item.pic === file.response.data.tmp_path
      }) 

      this.addRuleForm.pics.splice(i, 1)
    },
    handlePreview (file) {
      this.previewImg = file.response.data.url
      this.previewDialogVisible = true
    },
    handleSuccess (response, file, fileList) {
      let obj = {
        pic: response.data.tmp_path
      }

      this.addRuleForm.pics.push(obj)
    },
    addGood () { 
      this.$refs.addRuleFormRef.validate(async (valid) => {
        if (valid) {
          let obj = _.cloneDeep(this.addRuleForm)

          obj.goods_cat = obj.goods_cat.toString()

          obj.attrs = []

          obj.manyAttr.forEach(item => {
            let info = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.toString()
            }

            obj.attrs.push(info)
          })
          obj.onlyAttr.forEach(item => {
            let info = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }

            obj.attrs.push(info)
          })

          delete obj.fileList
          delete obj.manyAttr
          delete obj.onlyAttr
          
          const { data: res } = await this.$http.post('goods', obj)
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)

          this.$message.success(res.meta.msg)
          this.$router.push('/goods')

        } else {
          return this.$message.error('请填写完整表单信息')
        }
      })
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    cateId() {
      return this.addRuleForm.goods_cat[2]
    }
  }
}
</script>

<style lang="less">
.add-container {
  .ql-editor{
    height: 300px!important;
  }
  .el-card {
    margin: 20px 0;
  }
  .el-step__title {
    font-size: 12px;
  }
  .el-steps {
    margin: 20px 0;
  }
  .el-checkbox{
    margin: 0 10px 0 0 !important;
  }
  .add-good{
    margin-top: 20px;
  }
}
</style>